<script lang="ts">
    import { Tooltip } from "../Tooltip";
    import { useClassList } from "../utils/useClassList";
    import type { TextProps } from "./Typography";

    const props: TextProps = $props();
    const { type, disabled, underline, link, deleted, strong, ellipsis, size, gradient, mark, code, icon, ...others } = props;

    const classList = $derived(
        useClassList(props, "cm-text", {
            [`cm-text-${props.type}`]: props.type,
            "cm-text-disabled": props.disabled,
            "cm-text-underline": props.underline,
            "cm-text-link": props.link,
            "cm-text-deleted": props.deleted,
            "cm-text-strong": props.strong,
            "cm-text-with-ellipsis": !!props.ellipsis,
            [`cm-text-${props.size || "normal"}`]: props.size,
        })
    );

    const showTooltip = $derived.by(() => typeof props.ellipsis === "object" && props.ellipsis.showTooltip);
    const tooltipOptions = () => {
        if (showTooltip && typeof (props.ellipsis as any).showTooltip === "object") {
            return (props.ellipsis as any).showTooltip;
        }
        return {
            content: props.children,
        };
    };
</script>

{#snippet text()}
    <span
        {...others}
        class={classList}
        style={props.style}
        style:background-image={props.gradient ? `linear-gradient(${props.gradient.join(",")})` : ""}
        style:-webkit-text-fill-color={props.gradient ? "transparent" : ""}
    >
        {#if props.mark}
            <mark>{@render props.children?.()}</mark>
        {:else if props.code}
            <code>{@render props.children?.()}</code>
        {:else if props.link}
            <a href={props.link}>{@render props.icon?.()}<span>{@render props.children?.()}</span></a>
        {:else}
            {@render props.children?.()}
        {/if}
    </span>
{/snippet}

{#if showTooltip}
    <Tooltip {...tooltipOptions()}>
        {@render text()}
    </Tooltip>
{:else}
    {@render text()}
{/if}
